package homework;

public class HomeWork43 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null){
            return null;
        }
        if(root.val== p.val||root.val==q.val){
            return root;
        }
        //如果再左边
        if(find(root.left,p)&&find(root.left,q)){
            return lowestCommonAncestor(root.left,p,q);
        }
        //如果在右边
        if(find(root.right,p)&&find(root.right,q)){
            return lowestCommonAncestor(root.right,p,q);
        }
        return root;
    }

    private Boolean find(TreeNode root, TreeNode p) {
        if(root==null){
            return false;
        }
        if(root.val== p.val){
            return true;
        }
        return find(root.left,p)||find(root.right,p);
    }
}
